package cn.taobaoke.restful.domain;

import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

@Repository
public class AccountsV2Repository {

    @PersistenceContext
    private EntityManager entityManager;

    private static final String QUERY = "SELECT id, agent_id, create_at, date, domain_id, income, is_admin, is_payed, real_account, update_at order_total FROM tb_accounts_"; // 拼接具体的订单表
    private static final String COUNT_QUERY = "SELECT COUNT(1) FROM tb_accounts_";

    public List<AccountsEntity> getAccounts(Long domainId, String domain) {
        String sql = QUERY + domain + "  order by date desc";
        Query query = entityManager.createNativeQuery(sql, AccountsEntity.class);
        return query.getResultList();
    }

    public Optional<AccountsEntity> findByIdAndDomain(Long id, Long domainId, String domain) {
        String sql = QUERY + domain + " WHERE id = :id";
        Query query = entityManager.createNativeQuery(sql, AccountsEntity.class);
        query.setParameter("id", id);
        List result = query.getResultList();
        if (result.size() > 0) {
            return Optional.of((AccountsEntity)result.get(0));
        }
        return Optional.empty();
    }

    public List<AccountsEntity> findByDomainAndAgentIdIn(Long domainId, String domain, Collection<Long> agentIds) {
        String sql = QUERY + domain + " WHERE agent_id in ( :agentIds )";
        Query query = entityManager.createNativeQuery(sql, AccountsEntity.class);
        String ids = "";
        for (Long id : agentIds) {
            ids += id + ",";
        }
        if (ids.length() > 0) ids = ids.substring(0, ids.length()-1);
        query.setParameter("agentIds", ids);
        return query.getResultList();
    }

    @Transactional
    public int setPayedByDateLessThan(String date, String domain) {
        String sql = "UPDATE tb_accounts_" + domain + " SET is_payed = true WHERE date < :year_month";
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter("year_month", date);
        return query.executeUpdate();
    }

    @Transactional
    public int save(AccountsEntity entity, String domain) {
        if (entity.getId() == null) {
            return saveAll(Arrays.asList(entity), domain);
        }
        return updateAll(Arrays.asList(entity), domain);
    }

    @Transactional
    public int saveAll(List<AccountsEntity> accountsEntities, String domain) {
        String sql = "INSERT INTO tb_accounts_" + domain + " (agent_id, create_at, date, domain_id, income, is_admin, is_payed, real_account, update_at, order_total) " +
                " VALUES (:agent_id, :create_at, :date, :domain_id, :income, :is_admin, :is_payed, :real_account, :update_at, :order_total)";
        Query query = entityManager.createNativeQuery(sql);
        int cnt = 0;
        for (AccountsEntity entity : accountsEntities) {
            setAccountParameters(query, entity);
            cnt += query.executeUpdate();
        }
        return cnt;
    }

    @Transactional
    public int updateAll(List<AccountsEntity> accountsEntities, String domain) {
        String sql = "UPDATE tb_accounts_" + domain + " SET " +
                " agent_id = :agent_id, create_at = :create_at, date = :date, domain_id = :domain_id, income = :income, is_admin = :is_admin, is_payed = :is_payed, real_account = :real_account, update_at = :update_at, order_total = :order_total " +
                " WHERE id = :id ";
        Query query = entityManager.createNativeQuery(sql);
        int cnt = 0;
        for (AccountsEntity entity : accountsEntities) {
            setAccountParameters(query, entity);
            query.setParameter("id", entity.getId());
            cnt += query.executeUpdate();
        }
        return cnt;
    }

    private void setAccountParameters(Query query, AccountsEntity entity) {
        query.setParameter("agent_id", entity.getAgentId());
        query.setParameter("create_at", entity.getCreateAt());
        query.setParameter("date", entity.getDate());
        query.setParameter("domain_id", entity.getDomainId());
        query.setParameter("income", entity.getIncome());
        query.setParameter("is_admin", entity.getIsAdmin());
        query.setParameter("is_payed", entity.getIsPayed());
        query.setParameter("real_account", entity.getRealAccount());
        query.setParameter("update_at", entity.getUpdateAt());
        query.setParameter("order_total", entity.getOrderTotal());
    }
}
